<template>
    <div>
        <a-form-model :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }">
            <a-form-model-item label="系统类型 (ST)">
                <a-select v-model="form.systemType" :loading="loading.getSystemType">
                    <a-select-option 
                        v-for="option in systemTypeOptions" 
                        :key="option" 
                        :value="option"
                    >
                        {{ option }}
                    </a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item label="分钟数据上报间隔 (分)">
                <a-select v-model="form.reportInterval">
                    <a-select-option 
                        v-for="option in reportIntervalOptions" 
                        :key="option" 
                        :value="option"
                    >
                        {{ option }}
                    </a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item label="HttpSampleOption">
                <a-input v-model="form.httpSampleOption" />
            </a-form-model-item>
            <a-form-model-item label="HMI">
                <a-input v-model="form.hmi" />
            </a-form-model-item>
            <a-form-model-item label="Level">
                <a-input v-model="form.level" />
            </a-form-model-item>
        </a-form-model>

        <a-tabs default-active-key="server1" type="card">
            <a-tab-pane key="server1" tab="Server1">
                <server-config v-model="form.server1" />
            </a-tab-pane>
            <a-tab-pane key="server2" tab="Server2" :force-render="true">
                <server-config v-model="form.server2" />
            </a-tab-pane>
            <a-tab-pane key="server3" tab="Server3" :force-render="true">
                <server-config v-model="form.server3" />
            </a-tab-pane>
        </a-tabs>

        <div style="text-align: center; margin-top: 24px;">
            <a-button 
                type="primary" 
                style="margin-right: 8px;" 
                :loading="loading.save"
                @click="handleSave"
            >
                {{ loading.save ? '正在保存...' : '保存' }}
            </a-button>
        </div>
    </div>
</template>

<script>
import { Button, message } from 'ant-design-vue'
import ServerConfig from './components/ServerConfig.vue'
import { SettingsTabManager } from '@/api/TabManager'

export default {
    name: 'Hj212Network',
    components: {
        ServerConfig,
        'a-button': Button
    },
    data() {
        return {
            settingsTabManager: new SettingsTabManager(),
            dataLoaded: false,
            timestamp: null, // 用于跟踪数据更新时间戳
            loading: {
                getSystemType: false,
                save: false
            },
            form: {
                systemType: '21: 地表水质量监测',
                reportInterval: '1',
                httpSampleOption: 'http://127.0.0.1:8889/v1/getAllVariab:',
                hmi: '/dev/COM1',
                level: '6',
                server1: {
                    enabled: false,
                    ip: '',
                    port: '',
                    mn: '000000000000000000000000',
                    pw: '000000',
                    protocolVersion: '2017',
                    heartbeatInterval: '30',
                    realtimeReportInterval: '30',
                    timeout: '10',
                    retryCount: '3',
                    minuteReportEnabled: true,
                    minuteReportInterval: '3',
                    hourReportEnabled: true,
                    dayReportEnabled: true
                },
                server2: {
                    enabled: false,
                    ip: '',
                    port: '',
                    mn: '000000000000000000000000',
                    pw: '000000',
                    protocolVersion: '2017',
                    heartbeatInterval: '30',
                    realtimeReportInterval: '30',
                    timeout: '10',
                    retryCount: '3',
                    minuteReportEnabled: true,
                    minuteReportInterval: '3',
                    hourReportEnabled: true,
                    dayReportEnabled: true
                },
                server3: {
                    enabled: false,
                    ip: '',
                    port: '',
                    mn: '000000000000000000000000',
                    pw: '000000',
                    protocolVersion: '2017',
                    heartbeatInterval: '30',
                    realtimeReportInterval: '30',
                    timeout: '10',
                    retryCount: '3',
                    minuteReportEnabled: true,
                    minuteReportInterval: '3',
                    hourReportEnabled: true,
                    dayReportEnabled: true
                }
            },
            systemTypeOptions: ['21: 地表水质量监测'],
            reportIntervalOptions: ['1', '2', '3', '4', '5', '6', '10', '12', '15', '20', '30']
        }
    },
    mounted() {
        console.log('🚀 [Hj212Network] 组件 mounted')
        this.getSystemType()
    },
    methods: {
        async getSystemType() {
            if (this.loading.getSystemType) return
            
            try {
                this.loading.getSystemType = true
                // 从后台获取系统类型选项列表
                const res = await this.settingsTabManager.getHj212SystemType()
                
                console.log('🔍 [Hj212Network] 获取系统类型选项:', res)
                if (res && res.code === 0 && res.data) {
                    try {
                        const settingsData = JSON.parse(res.data) 
                        // 更新系统类型选项
                        this.systemTypeOptions = settingsData
                        
                        if (this.systemTypeOptions.length > 0) {
                            // 判断 this.form.systemType是否为空
                            if (this.form.systemType == '') {
                                this.form.systemType = this.systemTypeOptions[0]
                            }
                        }
                    } catch (parseError) {
                        console.error('❌ [Hj212Network] 解析系统类型数据失败:', parseError)
                        // 如果解析失败，使用默认选项
                        this.systemTypeOptions = ['21: 地表水质量监测']
                    }
                } else {
                    console.log('⚠️ [Hj212Network] 获取系统类型响应无效:', res)
                    // 使用默认选项
                    this.systemTypeOptions = ['21: 地表水质量监测']
                }
            } catch (error) {
                console.error('❌ [Hj212Network] 获取系统类型失败:', error)
                // 如果获取失败，使用默认选项
                this.systemTypeOptions = ['21: 地表水质量监测']
            } finally {
                this.loading.getSystemType = false
            }
        },
        
        async handleSave() {
            if (this.loading.save) return
            
            try {
                this.loading.save = true
                console.log('保存HJ212网络配置:', this.form)
                
                // 调用API保存配置
                const res = await this.settingsTabManager.saveHj212NetworkSettings(JSON.stringify(this.form))
                if (res && res.code !== 0) {
                    throw new Error(res.msg)
                } 

                // 发送更新事件给父组件
                const updateTimestamp = new Date().getTime()
                this.$emit('settings-updated', {
                    hj212NetworkSettings: {
                        data: JSON.stringify(this.form),
                        timestamp: updateTimestamp
                    }
                })

                // 更新本地时间戳
                this.timestamp = updateTimestamp
                
                message.success('HJ212网络设置保存成功')
                
            } catch (error) {
                console.error('保存HJ212网络设置失败:', error)
                message.error('保存失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading.save = false
            }
        },
        
        // 更新数据的方法，供父组件调用
        updateData(settingsData) {
            console.log('🔄 [Hj212Network] 更新数据:', settingsData)
            
            // 如果传入null，执行强制重置操作
            if (settingsData === null) {
                console.log('🔄 [Hj212Network] 执行强制重置操作')
                // 重置表单数据为默认值
                this.form = {
                    systemType: '21: 地表水质量监测',
                    reportInterval: '1',
                    httpSampleOption: 'http://127.0.0.1:8889/v1/getAllVariab:',
                    hmi: '/dev/COM1',
                    level: '6',
                    server1: {
                        enabled: false,
                        ip: '',
                        port: '',
                        mn: '000000000000000000000000',
                        pw: '000000',
                        protocolVersion: '2017',
                        heartbeatInterval: '30',
                        realtimeReportInterval: '30',
                        timeout: '10',
                        retryCount: '3',
                        minuteReportEnabled: true,
                        minuteReportInterval: '3',
                        hourReportEnabled: true,
                        dayReportEnabled: true
                    },
                    server2: {
                        enabled: false,
                        ip: '',
                        port: '',
                        mn: '000000000000000000000000',
                        pw: '000000',
                        protocolVersion: '2017',
                        heartbeatInterval: '30',
                        realtimeReportInterval: '30',
                        timeout: '10',
                        retryCount: '3',
                        minuteReportEnabled: true,
                        minuteReportInterval: '3',
                        hourReportEnabled: true,
                        dayReportEnabled: true
                    },
                    server3: {
                        enabled: false,
                        ip: '',
                        port: '',
                        mn: '000000000000000000000000',
                        pw: '000000',
                        protocolVersion: '2017',
                        heartbeatInterval: '30',
                        realtimeReportInterval: '30',
                        timeout: '10',
                        retryCount: '3',
                        minuteReportEnabled: true,
                        minuteReportInterval: '3',
                        hourReportEnabled: true,
                        dayReportEnabled: true
                    }
                }
                this.dataLoaded = false
                this.timestamp = null
                console.log('✅ [Hj212Network] 强制重置完成')
                return
            }
            
            if (!settingsData || !settingsData.data) {
                console.log('⚠️ [Hj212Network] 没有数据或数据格式不正确，跳过更新')
                return
            }
            
            // 检查时间戳，避免重复更新
            if (settingsData.timestamp && this.timestamp === settingsData.timestamp) {
                console.log('⚠️ [Hj212Network] 时间戳相同，跳过重复更新:', settingsData.timestamp)
                return
            }

            try {
                this.form = JSON.parse(settingsData.data)
                console.log('🔄 [Hj212Network] 解析后的数据:', this.form)
                
                // 更新时间戳
                this.timestamp = settingsData.timestamp
                this.dataLoaded = true
                console.log('✅ [Hj212Network] 数据更新成功，时间戳:', this.timestamp)
                
            } catch (error) {
                console.error('❌ [Hj212Network] 数据更新失败:', error)
            }
        },
        
        // 获取当前配置数据
        getCurrentConfig() {
            return { ...this.form }
        }
    }
}
</script> 

<style scoped>
.ant-form-item {
    margin-bottom: 0;
}
</style> 